﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class UserRoleDA : IUserRoleDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string ROLE_ID = "@ROLE_ID";
        private string SQL_CHECK_USER_ROLE_ID_UNIQUE = " SELECT COUNT(1) FROM @_@USER_ROLE WHERE USER_ID = @USER_ID AND ROLE_ID = @ROLE_ID ";
        private string SQL_DELETE_USER_ROLE = " DELETE FROM @_@USER_ROLE WHERE USER_ID = @USER_ID AND ROLE_ID = @ROLE_ID ";
        private string SQL_INSERT_USER_ROLE = " INSERT INTO @_@USER_ROLE ( USER_ID, ROLE_ID, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @USER_ID, @ROLE_ID, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_SELECT_ALL_USER_ROLE = " SELECT  ROWID, USER_ID, ROLE_ID, TS, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE  FROM  @_@USER_ROLE ";
        private string SQL_UPDATE_USER_ROLE = " UPDATE @_@USER_ROLE SET UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE() WHERE USER_ID = @USER_ID AND ROLE_ID = @ROLE_ID  ";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string USER_ID = "@USER_ID";

        public bool CheckUserRoleIDUnique(string userID, string roleID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@ROLE_ID", roleID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_USER_ROLE_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckUserRoleIDUnique(DataBase dataBase, DbTransaction tran, string userID, string roleID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@ROLE_ID", roleID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_USER_ROLE_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteUserRole(string userID, List<string> whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    string StrSql = " DELETE FROM @_@USER_ROLE WHERE USER_ID = '" + userID + "' ";
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql.Replace("@_@", whLoginID[i]));
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteUserRole(DataBase dataBase, DbTransaction tran, string userID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    string StrSql = " DELETE FROM @_@USER_ROLE WHERE USER_ID = '" + userID + "' ";
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql.Replace("@_@", whLoginID[i]));
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserRole(DataBase dataBase, DbTransaction tran, string roleID, string userID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@ROLE_ID", roleID) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_ROLE.Replace("@_@", whLoginID[i]), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllUserRole(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_ROLE.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserRole(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_ROLE.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public DataSet GetUserRoleByQueryList(List<string> sqlWhere, UserRoleQueryEntity userroleQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_ROLE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!userroleQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, userroleQuery.CurrentPage, userroleQuery.PageSize, userroleQuery.SortField, userroleQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetUserRoleByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, UserRoleQueryEntity userroleQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_ROLE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!userroleQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, userroleQuery.CurrentPage, userroleQuery.PageSize, userroleQuery.SortField, userroleQuery.SortDirection);
            }
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public List<UserRoleInfo> GetUserRoleByUserID(string userID, string whLoginID)
        {
            List<UserRoleInfo> userRoleInfoList = new List<UserRoleInfo>();
            string sql = this.SQL_SELECT_ALL_USER_ROLE.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID) };
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                UserRoleInfo userRoleInfo = null;
                while (reader.Read())
                {
                    DateTime CS00002;
                    userRoleInfo = new UserRoleInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["ROLE_ID"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00002 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00002 = new DateTime()));
                    userRoleInfoList.Add(userRoleInfo);
                }
            }
            return userRoleInfoList;
        }

        public List<UserRoleInfo> GetUserRoleByUserID(DataBase dataBase, DbTransaction tran, string userID, string whLoginID)
        {
            List<UserRoleInfo> userRoleInfoList = new List<UserRoleInfo>();
            string sql = this.SQL_SELECT_ALL_USER_ROLE.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID) };
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            UserRoleInfo userRoleInfo = null;
            while (reader.Read())
            {
                DateTime CS00002;
                userRoleInfo = new UserRoleInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["ROLE_ID"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00002 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00002 = new DateTime()));
                userRoleInfoList.Add(userRoleInfo);
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return userRoleInfoList;
        }

        public int InsertUserRole(UserRoleInfo userroleInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserRole_Parameters(userroleInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertUserRole(DataBase dataBase, DbTransaction tran, UserRoleInfo userRoleInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserRole_Parameters(userRoleInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_UserRole_Parameters(UserRoleInfo userRoleInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.ROLE_ID, SqlDbType.VarChar, 20), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = userRoleInfo.UserID;
            paramArray[1].Value = userRoleInfo.RoleID;
            paramArray[2].Value = userRoleInfo.CreatedBy;
            paramArray[3].Value = userRoleInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateUserRole(UserRoleInfo userRoleInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserRole_Parameters(userRoleInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateUserRole(DataBase dataBase, DbTransaction tran, UserRoleInfo userRoleInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserRole_Parameters(userRoleInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_ROLE.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

